import {
  getSetting,
  chooseAddress,
  openSetting,
  showModal,
  showToast
} from "../../utils/asyncWx.js";
import regeneratorRuntime from '../../lib/runtime/runtime';
import {
  request
} from '../../request/index.js'
Page({
  async handleAddAddress() {
    //点击 收货地址
    try {
      // 1 获取 权限状态
      const res1 = await getSetting();
      const scopeAddress = res1.authSetting["scope.address"];
      // 2 判断 权限状态
      if (scopeAddress === false) {
        //3 先诱导用户打开授权页面 
        await openSetting();
      }
      // 4 调用获取收货地址的 api
      let address = await chooseAddress();
      address.all = address.provinceName + address.cityName + address.countyName + address.detailInfo;
      // console.log(address);
      // 5 存入缓存中
      wx.setStorageSync("address", address);

    } catch (error) {
      console.log(error);
    }
  },
  data: {
    address: {},
    cart: [],
    totalPrice: 0,
    totalNum: 0
  },
  handleItemChange(e) {
    // 获取被修改的商品的id
    const goods_id = e.currentTarget.dataset.id;
    // console.log(goods_id);
    // 获取购物车数组
    let {
      cart
    } = this.data;
    // 找到被修改的商品对象
    let index = cart.findIndex(v => v.goods_id === goods_id);

    // 选中状态取反
    cart[index].checked = !cart[index].checked;
    this.setCart(cart);
  },

  onShow() {
    //1 获取缓存中的收货地址
    const address = wx.getStorageSync('address');

    //获取缓存中的购物车数据
    let cart = wx.getStorageSync("cart") || [];
    cart = cart.filter(v => v.checked);
    // every用法，数组遍历方法，会遍历 会接受一个回调函数 每一个回调函数都返回TRUE 则every方法的返回值也是TRUE
    // 只要有一个回调函数反悔了FALSE 则不在循环执行 直接返回FALSE
    // 空数组调动every方法 返回值就是TRUE
    let allChecked = cart.length ? cart.every(v => v.checked) : false;
    //2 赋值
    this.setData({
      address
    });

    let totalPrice = 0;
    let totalNum = 0;
    cart.forEach(v => {
      totalPrice += v.num * v.goods_price;
      totalNum += v.num;
    })

    //2 赋值
    this.setData({
      cart,
      address,
      totalPrice,
      totalNum
    });
  },
  async handleOrderPay() {
    try {
      // 判断缓存是否有token
      const token = wx.getStorageSync("token");
      console.log(token);
      if (!token) {
        wx.navigateTo({
          url: '/pages/auth/auth'
        });
        return;
      }
      console.log("token存在!");
      // 3 创建订单
      // 3.1 准备 请求头参数
      // const header = {
      //   Authorization: token
      // };
      // 3.2 准备 请求体参数
      const order_price = this.data.totalPrice;
      const consignee_addr = this.data.address.all;
      const cart = this.data.cart;
      let goods = [];
      cart.forEach(v => goods.push({
        goods_id: v.goods_id,
        goods_number: v.num,
        goods_price: v.goods_price
      }))
      //  发送请求
      const orderParams = {
        order_price,
        consignee_addr,
        goods
      };
      // 4 准备发送请求 创建订单获取订单编号
      const {
        order_number
      } = await request({
        url: "/my/orders/create",
        method: "POST",
        data: orderParams
      });
      console.log(order_number);


      // 发起预支付 
      const {
        pay
      } = await request({
        url: "/my/orders/req_unifieorder",
        method: "POST",
        data: {
          order_number
        }
      });
      console.log(res);

      // 发起微信支付 
      await requestPayment(pay);
      // 查询订单 
      const res = await request({
        url: "/my/orders/chkOrder",
        method: "Post",
        data: {
          order_number
        }
      });
      await showToast({
        title: "支付成功！"
      });

      // 这里因为没有token无效，所以将跳转页面以及查询订单的效果放在失败状态下 
      let newCart = wx.getStorageSync('cart'); 
      newCart = newCart.filter(v => !v.checked); 
      wx.setStorageSync('cart', newCart); 
      // const token = wx.getStorageSync("token");
      if (token) {
        wx.navigateTo({
          url: '/pages/order/order'
        })
      }
    } catch (error) {
      await showToast({
        title: "支付失败！"
      });

      // let newCart = wx.getStorageSync('cart');
      // newCart = newCart.filter(v => !v.checked);
      // wx.setStorageSync('cart', newCart);
      // // 判断缓存是否有token 
      // const token = wx.getStorageSync("token");
      // if (!token) {
      //   wx.navigateTo({
      //     url: '/pages/order/order'
      //   })
      // }
    }
  }

})